<template>
  <div>
    <el-button @click="connectSocket">连接Socket</el-button>
    <el-button @click="sendMessage" >发送消息1</el-button>
    <el-input v-model="inputMessage.content" placeholder="输入要发送的消息"></el-input>
    <el-card class="box-card">
      <div v-for="(msg, index) in receivedMessages" :key="index">{{ msg }}</div>
    </el-card>
  </div>
</template>

<script>
// 导入socket.io-client创建Socket实例

// 导入vue-socket.io用于在Vue中集成Socket功能
//import VueSocketIO from 'vue-socket.io';
import io from'socket.io-client';
export default {
  data() {
    return {
      socket: null, // 用于保存Socket实例，替代原来的stompClient
      isConnected: false,
      inputMessage: {
        userId: "2",
        content: ""
      },
      receivedMessages: []
    };
  },
  methods: {
    //发送消息的方法(前端给后端发送)
    sendMessage() {
      //发送数据 emit("事件名称",数据) ，事件名称是自定义的
      this.socket.emit('messageevent', JSON.stringify(this.inputMessage));
      this.inputMessage.content = '';
    }
  },
  //生命周期函数,mounted函数在组件挂载后执行
  mounted() {
    //连接后端服务器
    this.socket = io('http://localhost:9097?userId=1');
    //监听连接事件
    this.socket.on('connect', () => {
      console.log('Connected to server');
    });
    //接收数据(后端返回前端的数据)  on("事件名称",回调函数) -事件名是自定义的，基于监听器实现
    this.socket.on('pushEvent', (data) => {
      console.log('来自服务器的数据:', data);
      this.receivedMessages.push(data);
    });
  },
  //生命周期函数,在组件销毁前执行
  beforeDestroy() {
    if(this.socket){
      this.socket.disconnect();
    }
  }

};
</script>

<style scoped>
.box-card {
  margin-top: 10px;
}
</style>
